package cn.ug.activity.web.controller;

import cn.ug.activity.mapper.entity.ActivityInvitation;
import cn.ug.activity.mapper.entity.ActivityInvitationStrategy;
import cn.ug.activity.mapper.entity.ActivityInvitationTop;
import cn.ug.activity.mq.RewardsReceiver;
import cn.ug.activity.service.ActivityInvitationService;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.util.BigDecimalUtil;
import cn.ug.util.PaginationUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("invitation")
public class ActivityInvitationController {
    @Autowired
    private ActivityInvitationService activityInvitationService;

    @GetMapping(value = "/list")
    public SerializeObject<DataTable<ActivityInvitation>> list(@RequestHeader String accessToken, Page page) {
        int total = activityInvitationService.count("");
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<ActivityInvitation> list = activityInvitationService.query(offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<ActivityInvitation>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<ActivityInvitation>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<ActivityInvitation>()));
    }

    @GetMapping(value = "/tops")
    public SerializeObject<List<ActivityInvitationTop>> getTopList() {
        ActivityInvitation activityInvitation = activityInvitationService.selectValidActivity();
        if (activityInvitation != null) {
            List<ActivityInvitationTop> tops = activityInvitationService.queryTop10(activityInvitation.getId(), activityInvitation.getStartDate(), activityInvitation.getEndDate());
            if (tops != null && tops.size() > 0) {
                for (ActivityInvitationTop bean : tops) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(bean.getMobile())) {
                        bean.setMobile(org.apache.commons.lang3.StringUtils.substring(bean.getMobile(), 0, 3) +"****"+ org.apache.commons.lang3.StringUtils.substring(bean.getMobile(), 7));
                    }
                }
            }
            return new SerializeObject<>(ResultType.NORMAL, tops);
        } else {
            return new SerializeObject<>(ResultType.NORMAL, activityInvitationService.queryTop10(0, "", ""));
        }
    }

    @GetMapping(value = "/strategies")
    public SerializeObject<List<ActivityInvitationStrategy>> getStrategyList() {
        ActivityInvitation activityInvitation = activityInvitationService.selectValidActivity();
        if (activityInvitation != null) {
            List<ActivityInvitationStrategy> strategies = activityInvitationService.queryForList(activityInvitation.getId());
            if (strategies != null && strategies.size() > 0) {
                return new SerializeObject<>(ResultType.NORMAL, strategies);
            } else {
                return new SerializeObject<>(ResultType.NORMAL, activityInvitationService.queryForLatestList());
            }
        } else {
            return new SerializeObject(ResultType.ERROR, "00000003");
        }
    }

    @GetMapping(value = "/detail")
    public SerializeObject<ActivityInvitation> getDetail(@RequestHeader String accessToken, int activityId) {
        return new SerializeObject<>(ResultType.NORMAL, activityInvitationService.get(activityId));
    }

    @GetMapping(value = "/valid")
    public SerializeObject<JSONObject> getValidActivity() {
        ActivityInvitation activityInvitation = activityInvitationService.selectValidActivity();
        if (activityInvitation != null) {
            return new SerializeObject<>(ResultType.NORMAL, JSON.parseObject(JSONObject.toJSONString(activityInvitation)));
        } else {
            return new SerializeObject(ResultType.ERROR, "00000003");
        }
    }

    @PostMapping("/close")
    public SerializeObject close(@RequestHeader String accessToken, int activityId) {
        if (activityInvitationService.close(activityId)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/delete")
    public SerializeObject delete(@RequestHeader String accessToken, int activityId) {
        if (activityInvitationService.delete(activityId)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, ActivityInvitation activityInvitation, String strategyList) {
        if (activityInvitation == null || StringUtils.isBlank(activityInvitation.getName())) {
            return new SerializeObjectError("22000104");
        }
        if (StringUtils.isBlank(activityInvitation.getStartDate())) {
            return new SerializeObjectError("22000105");
        }
        if (StringUtils.isBlank(activityInvitation.getEndDate())) {
            return new SerializeObjectError("22000106");
        }

        if (StringUtils.isBlank(strategyList)) {
            return new SerializeObjectError("22000107");
        }
        List<ActivityInvitationStrategy> activityInvitationStrategies = null;
        try {
            activityInvitationStrategies = JSONArray.parseArray(strategyList, ActivityInvitationStrategy.class);
            if (activityInvitationStrategies == null || activityInvitationStrategies.size() == 0) {
                return new SerializeObjectError("22000107");
            }
            for (ActivityInvitationStrategy strategy : activityInvitationStrategies) {
                if (strategy == null || strategy.getInvestmentAmount() == null || strategy.getInvestmentAmount().doubleValue() <= 0) {
                    return new SerializeObjectError("22000108");
                }
                if (strategy.getProportion() == null || strategy.getProportion().doubleValue() <= 0) {
                    return new SerializeObjectError("22000109");
                }
            }
        } catch (Exception e) {
            return new SerializeObjectError("22000112");
        }
        int id = activityInvitationService.save(activityInvitation, activityInvitationStrategies);
        if (id > 0) {
            ActivityInvitation activity = activityInvitationService.get(id);
            JSONObject result = new JSONObject();
            result.put("id", id);
            if (activity != null) {
                result.put("status", activity.getStatus());
            }
            return new SerializeObject(ResultType.NORMAL, "00000001", activity);
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/top")
    public SerializeObject saveTops(@RequestHeader String accessToken, String topList) {
        List<ActivityInvitationTop> activityInvitationTops = null;
        try {
            if (StringUtils.isBlank(topList)) {
                return new SerializeObjectError("22000113");
            }
            activityInvitationTops = JSONArray.parseArray(topList, ActivityInvitationTop.class);
            if (activityInvitationTops == null || activityInvitationTops.size() == 0) {
                return new SerializeObjectError("22000110");
            }
            for (ActivityInvitationTop top : activityInvitationTops) {
                if (top == null || StringUtils.isBlank(top.getMobile())) {
                    return new SerializeObjectError("22000110");
                }
                if (top.getInvestmentAmount() == null || top.getInvestmentAmount().doubleValue() <= 0) {
                    return new SerializeObjectError("22000111");
                }
                if (top.getActivityInvitationId() == 0) {
                    return new SerializeObjectError("22000115");
                }
            }
        } catch (Exception e) {
            return new SerializeObjectError("22000113");
        }
        if (activityInvitationService.save(activityInvitationTops)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping("/rewards")
    public SerializeObject getRewards(int activityId, BigDecimal payAmount) {
        JSONObject result = new JSONObject();
        result.put("inviterRewards", 0);
        result.put("invitorRewards", 0);
        ActivityInvitation activityInvitation = activityInvitationService.get(activityId);
        if (activityInvitation.getStrategyies() == null || activityInvitation.getStrategyies().size() == 0) {
            return new SerializeObject(ResultType.NORMAL, "00000001", result);
        }
        if (payAmount == null || payAmount.doubleValue() <= 0) {
            return new SerializeObject(ResultType.NORMAL, "00000001", result);
        }
        List<ActivityInvitationStrategy> strategies = activityInvitation.getStrategyies();
        double income = RewardsReceiver.computeIncomeAmount(payAmount.doubleValue(), 0, strategies);
        result.put("inviterRewards", BigDecimalUtil.to2Point(new BigDecimal(income).multiply(new BigDecimal(0.7))));
        result.put("invitorRewards", BigDecimalUtil.to2Point(new BigDecimal(income).multiply(new BigDecimal(0.3))));
        return new SerializeObject(ResultType.NORMAL, "00000001", result);
    }
}
